import { LoginService } from '../services/login.service';
import {
  Directive,
  Input,
  ElementRef,
  Renderer,
  HostListener,
  ViewContainerRef,
  TemplateRef
} from '@angular/core';

@Directive({
  selector: '[authority]'
})
export class AuthDirective {

    user: any;

    @Input('authority')

    set condition(newCondition: any) {
        // console.log('AuthDirective: ', newCondition);
        if (newCondition) {
            // ["recipes/list/1", "recipes/list/110"]   newCondition
            // ["recipes/list/1", "recipes/list/110"]   this.user['authList']
            let bool = false;
            if (newCondition.length > 1) {
                let oi = 0;
                newCondition.forEach(ite => {
                    const op = this.user['authList'].find(i => i === ite);
                    if (op) {
                        oi++;
                    }
                });
                if (oi === newCondition.length) {
                    bool = true;
                }
            } else {
                let oi = this.user['authList'].find(i => i === newCondition[0]);
                if (oi) {
                    bool = true;
                }
            }
            // newCondition 2
            // bool 1
            if (bool) { // 创建模板对应的内嵌视图
                this.viewContainer.createEmbeddedView(this.templateRef);
            } else {
                this.viewContainer.clear();
            }
        }
    }

    constructor(
        private templateRef: TemplateRef<any>,
        private loginService: LoginService,
        private viewContainer: ViewContainerRef
    ) {
        this.user = this.loginService.getUser();
        // console.log(this.user['authList']);
    }
}